from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
import os
import urllib


#Applicant Report Model Class
class modelReport(db.Model):
	Applicant = db.StringProperty()
	Reportblob = blobstore.BlobReferenceProperty()

class MainHandler(webapp.RequestHandler):
    def get(self):
        upload_url = blobstore.create_upload_url('/upload')
        # The method must be "POST" and enctype must be set to "multipart/form-data".
        self.response.out.write('<html><body>ResEdge Retrieve Results Page 07-08-2012<p>')
        self.response.out.write('<form action="/retrieve_results/upload_handler" method="POST" enctype="multipart/form-data">')
#        self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url)
        self.response.out.write('''Upload File: <input type="file" name="file"><br>Applicant Username: <input type="text" name="txtApplicantName" /><br><input type="submit" name="submit" value="Submit"></form><p></p><a href="/retrieve_results/upload_results">Upload Results</a></p><a href="/retrieve_results/retrieve_results">Retrive Results</a></p><a href="/">Home Page</a></p><hr></body></html>''')

#Store Applicant Report Class
#class UploadResults(webapp.RequestHandler):
#	def post(self):
#		m = modelReport()
#		m.Applicant = self.request.get("txtApplicantName")
#		Reportblob = self.request.get("file")
#		m.Reportblob = db.Blob(Reportblob)
#		m.put()
#		self.redirect('/UploadResultsClassSuccessful')
		
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        try:
            upload_files = self.get_uploads('file')
            blob_info = upload_files[0]

            m = modelReport()
            m.Applicant = self.request.get('txtApplicantName')
            m.blobkey = blob_info.key()
            m.put()

            self.redirect('/')
        except:
            self.redirect('/upload_failure.html')

class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
  def get(self, resource):
    resource = str(urllib.unquote(resource))
    blob_info = blobstore.BlobInfo.get(resource)
    type = blob_info.content_type
    if type == 'application/pdf':
    	self.response.headers['Content-Type'] = type
    	self.send_blob(blob_info,save_as=False)
    else:
    	self.send_blob(blob_info, save_as=True)

'''  Last Try *****************
class UploadResults(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        try:
            upload = self.get_uploads()[0]
            results = modelReport("txtApplicantName", blob_key=upload.key())
            db.put(results)
            self.redirect('/retrieve_results/view_results/%s' % upload.key())
        except:
            self.redirect('/upload_failure.html')
            
class ViewResults(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self, blob_key):
        if not blobstore.get(blob_key):
            self.error(404)
        else:
            self.send_blob(blob_key)
'''   #End of Last Try ******************

application = webapp.WSGIApplication([
	('/retrieve_results/', MainHandler),
	('/retrieve_results/upload_handler', UploadHandler),
	('/serve/([^/]+)?', ServeHandler),
    ], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()